package com.test.order;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.persist.StateMachinePersister;

import java.util.EnumSet;

/**
 * @author 魏彪
 */
@Configuration
@EnableStateMachine(name = "orderStateMachine")
@Slf4j
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderState, OrderEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {
        states.withStates()
                .initial(OrderState.WAIT_PAYMENT)
                .states(EnumSet.allOf(OrderState.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) throws Exception {
        transitions.withExternal()
                .source(OrderState.WAIT_PAYMENT)
                .target(OrderState.WAIT_DELIVER)
                .event(OrderEvent.PAYED)
                .and()
                .withExternal()
                .source(OrderState.WAIT_DELIVER)
                .target(OrderState.WAIT_RECEIVE)
                .event(OrderEvent.DELIVERY)
                .and()
                .withExternal()
                .source(OrderState.WAIT_RECEIVE)
                .target(OrderState.FINISH)
                .event(OrderEvent.RECEIVED);
    }

    @Bean
    public StateMachinePersister<OrderState, OrderEvent, Order> stateMachinePersister() {
        return new DefaultStateMachinePersister<>(new StateMachinePersist<OrderState, OrderEvent, Order>() {
            @Override
            public void write(StateMachineContext<OrderState, OrderEvent> stateMachineContext, Order order) throws Exception {
                log.info("======持久化入库======");
            }

            @Override
            public StateMachineContext<OrderState, OrderEvent> read(Order order) throws Exception {
                return null;
            }
        });
    }
}
